<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="500px">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-form-item label="关联企业" prop="companyId">
        <el-input v-model="companyInfo.name" disabled placeholder="关联企业" />
      </el-form-item>
      <el-form-item label="股东姓名" prop="shareholderName">
        <el-input v-model="formData.shareholderName" placeholder="请输入股东姓名" />
      </el-form-item>
      <el-form-item label="持股比例" prop="shareholdingRatio">
        <el-input-number v-model="formData.shareholdingRatio" :min="0" :max="100" :precision="2" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { DICT_TYPE } from '@/utils/dict'
import { CompanyShareholdersApi } from '@/api/oa/companyshareholders/index'
import { AccountingCompaniesApi } from '@/api/oa/accountingcompanies'

/** 企业股东信息 表单 */
defineOptions({ name: 'CompanyShareholdersForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const props = defineProps<{
  type: string
  id?: number
  companyId?: number
  companyName?: string // 关联企业名称
  businessType?: string
  readonly?: boolean
}>()

/** 表单对象 */
const formData = ref<CompanyShareholdersVO & { businessType?: string }>({
  id: 0,
  companyId: 0,
  shareholderName: '',
  shareholdingRatio: 0,
  creatorName: '',
  updaterName: '',
  businessType: props.businessType
})

// 企业信息
const companyInfo = ref({
  id: 0,
  name: ''
})

/** 表单校验 */
const formRules = reactive({
  companyId: [{ required: true, message: '关联的企业ID不能为空', trigger: 'blur' }],
  shareholderName: [{ required: true, message: '股东姓名不能为空', trigger: 'blur' }],
  shareholdingRatio: [{ required: true, message: '持股比例不能为空', trigger: 'blur' }],
})

const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number, data?: any) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 设置关联企业信息
  if (data?.companyId) {
    formData.value.companyId = data.companyId
    formData.value.companyName = data.companyName
    formData.value.businessType = data.businessType
  }
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await CompanyShareholdersApi.getCompanyShareholders(id)
      formData.value.businessType = props.businessType
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value
    if (!data.id) {
      // 新增
      await CompanyShareholdersApi.createCompanyShareholders({
        companyId: data.companyId,
        shareholderName: data.shareholderName,
        shareholdingRatio: data.shareholdingRatio,
        businessType: data.businessType
      })
      message.success(t('common.createSuccess'))
    } else {
      // 编辑
      await CompanyShareholdersApi.updateCompanyShareholders({
        id: data.id,
        companyId: data.companyId,
        shareholderName: data.shareholderName,
        shareholdingRatio: data.shareholdingRatio,
        businessType: data.businessType
      })
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 通知操作成功
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    companyId: props.companyId,
    companyName: props.companyName,
    businessType: props.businessType,
    shareholderName: undefined,
    shareholdingRatio: undefined,
    creatorName: undefined,
    updaterName: undefined,
    createTime: undefined,
    updateTime: undefined,
    creator: undefined,
    updater: undefined,
    deleted: false
  }
  formRef.value?.resetFields()
}
</script>